@file:Suppress("unused")

package com.hjh.tool.util

import android.content.res.AssetManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.media.Image
import java.io.IOException
import java.io.InputStream
import java.nio.ByteBuffer
import kotlin.let
import kotlin.ranges.coerceIn
import kotlin.ranges.until
import androidx.core.graphics.createBitmap

/**
 * @author： hjh
 * @createDate： 2025/2/20 17:01
 * @description：
 * @qq： 3472903821
 * @version: 1.0
 */
object VideoUtil {

    /**
     * Image 转 ARGB
     */
    fun Image.toRGBA8888Bitmap(): Bitmap {
        val planes = planes
        val buffer: ByteBuffer = planes[0].buffer
        val pixelStride = planes[0].pixelStride
        val rowStride = planes[0].rowStride
        val rowPadding = rowStride - pixelStride * width

        val bitmap = createBitmap(width + rowPadding / pixelStride, height)

        bitmap.copyPixelsFromBuffer(buffer)
        return bitmap
    }

    /**
     * Image 提取 YUV, YUV 转 ARGB
     */
    fun Image.toBitmapYUV420ToRGBA(): Bitmap {
        val yuvBuffer = getYUVBytes() // 提取 YUV 数据
        val argb8888 = ByteArray(width * height * 4) // RGBA_8888 数据

        yuv420ToArgb8888(
            yuvBuffer, width, height,
            argb8888
        )

        val bitmap = createBitmap(width, height)
        bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(argb8888))
        return bitmap
    }

    /**
     * Image 中获取 YUV 格式
     */
    private fun Image.getYUVBytes(): ByteArray {
        val width = width
        val height = height
        val ySize = width * height
        val uvSize = ySize / 2 // NV21 格式的 UV 交错存储

        val nv21 = ByteArray(ySize + uvSize) // 存储 NV21 格式数据
        var dstIndex = 0

        // 获取 Y 平面
        val yBuffer = planes[0].buffer
        val yRowStride = planes[0].rowStride
        val yPixelStride = planes[0].pixelStride

        for (row in 0 until height) {
            for (col in 0 until width) {
                nv21[dstIndex++] = yBuffer.get(row * yRowStride + col * yPixelStride)
            }
        }

        // 获取 UV 平面（交错存储）
        val uBuffer = planes[1].buffer
        val vBuffer = planes[2].buffer
        val uvRowStride = planes[1].rowStride
        val uvPixelStride = planes[1].pixelStride

        for (row in 0 until height / 2) {
            for (col in 0 until width / 2) {
                val uIndex = row * uvRowStride + col * uvPixelStride
                val vIndex = row * uvRowStride + col * uvPixelStride
                nv21[dstIndex++] = vBuffer.get(vIndex) // V 分量
                nv21[dstIndex++] = uBuffer.get(uIndex) // U 分量
            }
        }
        return nv21
    }

    /**
     * YUV 转 ARGB
     */
    private fun yuv420ToArgb8888(yuv: ByteArray, width: Int, height: Int, rgba: ByteArray) {
        val frameSize = width * height
        val uvOffset = frameSize // U/V 数据起始偏移量

        var rgbaIndex = 0

        for (j in 0 until height) {
            for (i in 0 until width) {
                val yIndex = j * width + i
                val uvRow = (j shr 1) * (width shr 1)
                val uvCol = (i shr 1)

                val uIndex = uvOffset + uvRow + uvCol
                val vIndex = uvOffset + (frameSize / 4) + uvRow + uvCol

                val y = (yuv[yIndex].toInt() and 0xFF) - 16
                val u = (yuv[uIndex].toInt() and 0xFF) - 128
                val v = (yuv[vIndex].toInt() and 0xFF) - 128

                val r = (1.164f * y + 1.596f * v).toInt().coerceIn(0, 255)
                val g = (1.164f * y - 0.392f * u - 0.813f * v).toInt().coerceIn(0, 255)
                val b = (1.164f * y + 2.017f * u).toInt().coerceIn(0, 255)

                rgba[rgbaIndex++] = r.toByte()
                rgba[rgbaIndex++] = g.toByte()
                rgba[rgbaIndex++] = b.toByte()
                rgba[rgbaIndex++] = 255.toByte() // Alpha = 255
            }
        }
    }

    fun loadImageFromAssets(assets: AssetManager, fileName: String?): Bitmap? {
        try {
            val inputStream: InputStream? = fileName?.let { assets.open(it) }
            return BitmapFactory.decodeStream(inputStream)
        } catch (e: IOException) {
            e.printStackTrace()
            return null
        }
    }

    fun convertToARGB8888(original: Bitmap): Bitmap {
        if (original.config == Bitmap.Config.ARGB_8888) {
            return original // 已经是目标格式，直接返回
        }

        // 创建目标 Bitmap
        val argbBitmap = createBitmap(original.width, original.height)

        val canvas = Canvas(argbBitmap)
        val paint = Paint()

        // 处理 RGB_565 等无 Alpha 的情况
        if (original.config == Bitmap.Config.RGB_565) {
            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
            paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
        }

        canvas.drawBitmap(original, 0f, 0f, paint)
        return argbBitmap
    }
}